<template>
  <a-modal
    v-model="visible"
    title="批量导入物流运单"
    cancelText="取消"
    okText="确定"
    @ok="handleOk"
    width="50%"
  >
    <div style="display: flex; width: 55%; margin: 10px 0">
      <div style="flex: 1">
        <template>
          <a-upload
            name="file"
            :multiple="true"
            :action="baseUrl + '/by-outbound-apply/upLoad'"
            :headers="headers"
            :file-list="fileListByState"
            @change="handleChangeUpLoad"
          >
            <a-button type="primary" size="small">
              <a-icon type="upload" /> 上传文件
            </a-button>
          </a-upload>
        </template>
      </div>
      <div style="flex: 1">
        <a
          @click="upDow"
          style="
            margin-left: 20px;
            text-decoration: underline;
            color: rgb(41, 41, 224);
            flex: 1;
          "
          href="javascript:;"
          >下载订单物流数据模板</a
        >
      </div>
    </div>
    <a-table
      :columns="columns"
      :data-source="tableDatas"
      :pagination="false"
      :scroll="{ y: 400, x: 770 }"
      bordered
      size="small"
    >
      <span slot="ectnFile" class="action" slot-scope="text, record">
        <a-upload
          v-if="record.ectnFile === '' || record.ectnFile === null"
          :beforeUpload="beforeUploads"
          name="file"
          :multiple="true"
          :file-list="fileList"
          :action="baseUrl + '/by-file/uploadFile'"
          :headers="headersRow"
          @change="(fileList) => handleChangeRow(fileList, record)"
        >
          <a-button size="small"> <a-icon type="upload" /> 上传文件 </a-button>
        </a-upload>
        <div
          class="flie-list"
          v-if="record.ectnFile != '' && record.ectnFile != null"
        >
          <a
            target="_blank"
            v-if="record.ectnFile != '' && record.ectnFile != null"
            :href="record.ectnFile"
            download="运单文件"
            >{{ record.fileName.substring(0, 18) }}...
          </a>
          <a-icon
            v-if="record.ectnFile != '' && record.ectnFile != null"
            @click.stop="delFiles(record)"
            style="color: #000; margin-left: 10px"
            type="delete"
            theme="filled"
          />
        </div>
      </span>
      <span slot="logisticsName" slot-scope="text, record">
        <a-select
          placeholder="请选择物流商"
          size="small"
          show-search
          option-filter-prop="children"
          style="width: 100%"
          @change="
            (value, option) => handleChangeLogistics(value, option, record)
          "
        >
          <a-select-option
            v-for="item in logisticsArray"
            :value="item.id"
            :key="item.id"
            :logisticsPlatform="item.logisticsPlatform"
            :serviceName="item.serviceName"
            :sysLogisticsId="item.sysLogisticsId"
            :sysLogisticsServiceItemId="item.sysLogisticsServiceItemId"
          >
            <a-tooltip>
              <template slot="title">
                {{ item.serviceName }}/{{ item.logisticsPlatform }}
              </template>
              {{ item.serviceName }}/{{ item.logisticsPlatform }}
            </a-tooltip>
          </a-select-option>
        </a-select>
      </span>
      <span slot="logisticsService" slot-scope="text, record">
        <a-select
          size="small"
          show-search
          option-filter-prop="children"
          style="width: 100%"
          @change="
            (value, option) => changeLogisticsServiceArry(value, option, record)
          "
        >
          <a-select-option
            v-for="item in logisticsServiceArry"
            :value="item.wayName"
            :sysLogisticsServiceWayTenantId="
              item.sysLogisticsServiceWayTenantId
            "
            :key="item.sysLogisticsServiceWayTenantId"
          >
            {{ item.wayName }}
          </a-select-option>
        </a-select>
      </span>
      <span slot="logisticsCost" slot-scope="text, record">
        <a-input-number
          style="width: 100%"
          size="small"
          v-model="record.logisticsCost"
          :min="0"
        />
      </span>
      <span slot="ectnNo" slot-scope="text, record">
        <a-input
        :maxLength="128"
          style="width: 100%"
          size="small"
          v-model="record.ectnNo"
          :min="0"
        />
      </span>
    </a-table>
  </a-modal>
</template>


<script>
import { mapState } from "vuex";
import {
  OutboundBatchByState_upDow,
  OutboundBatchByState_updateIsectn,
  OutboundBatchByState_removefile,
} from "@/apis/clientSide/OrderManage/Outbound";
import { selectTenantIdAllServerName } from "@/apis/common";
import baseUrl from "@/utils/baseUrl";
export default {
  props: ["getOutboundTableList", "getStateCount", "selectedKeys"],
  data() {
    return {
      logisticsServiceArry: [],
      logisticsList: [],
      passFlag: true,
      fileName: "",
      // 上传标杆
      uploadFlag: false,
      fileListByState: [],
      fileList: [],
      baseUrl,
      visible: false,
      headers: {
        authorization: "authorization-text",
        token: sessionStorage.getItem("tk"),
      },
      headersRow: {
        authorization: "authorization-text",
        token: sessionStorage.getItem("tk"),
      },
      tableDatas: [],
    };
  },
  created() {
    // this.getLogisticsList();
  },
  methods: {
    // 物流商更改
    async handleChangeLogistics(value, option, record) {
      record.logisticsName = option.data.attrs.name;
      record.logisticsName =
        option.data.attrs.serviceName +
        "/" +
        option.data.attrs.logisticsPlatform;
      record.logisticsId =
        option.data.attrs.sysLogisticsId +
        "," +
        option.data.attrs.sysLogisticsServiceItemId;
      let { code, responseBody } = await selectTenantIdAllServerName(
        option.data.attrs.sysLogisticsId,
        option.data.attrs.sysLogisticsServiceItemId,
        sessionStorage.getItem("tenantId")
      );
      if (code === "200") {
        this.logisticsServiceArry = responseBody;
      }
    },
    //物流方式更改
    changeLogisticsServiceArry(value, option, record) {
      record.logisticsService = value;
      record.logisticsServiceId =
        option.data.attrs.sysLogisticsServiceWayTenantId;
    },
    //限制上传图片大小
    // 限制上传文件
    beforeUploads(file) {
      return new Promise((resolve, reject) => {
        this.files = file;
        const pdf = file.type === "application/pdf";
        const isLt6M = file.size / 1024 / 1024 < 6;
        const img =
          file.type === "image/jpeg" ||
          file.type === "image/png" ||
          file.type === "image/jpg";
        if (!pdf && !img) {
          this.$message.error("上传文件只能是 png、jpg、jpeg、PDF!");
          return reject(false);
        }
        if (!isLt6M) {
          this.$message.error("文件大小限制小于6MB!");
          return reject(false);
        }
        return resolve(true);
      });
    },
    // 导出运单文件
    async upDow() {
      let res = await OutboundBatchByState_upDow();
      const blob = new Blob([res], {
        type: "application/vnd.ms-excel",
      });
      const fileName = "物流数据模板.xlsx";
      const linkNode = document.createElement("a");
      linkNode.download = fileName; //a标签的download属性规定下载文件的名称
      linkNode.style.display = "none";
      linkNode.href = URL.createObjectURL(blob); //生成一个Blob URL
      document.body.appendChild(linkNode);
      linkNode.click(); //模拟在按钮上的一次鼠标单击
      URL.revokeObjectURL(linkNode.href); // 释放URL 对象
      document.body.removeChild(linkNode);
    },
    async handleOk() {
      this.passFlag = true;
      if (this.tableDatas.length <= 0) {
        this.$message.error("请上传文件后提交！");
        return false;
      }

      this.tableDatas.forEach((item) => {
        item.waybillFile = Array.isArray(item.waybillFile)
          ? item.waybillFile.join(",")
          : item.waybillFile;

        if (
          item.ectnFile === null ||
          item.ectnFile === "" ||
          item.ectnFile === undefined
        ) {
          this.passFlag = false;
          return false;
        }

        if (
          item.logisticsName === null ||
          item.logisticsName === "" ||
          item.logisticsName === undefined
        ) {
          this.passFlag = false;
          return false;
        }
        if (
          item.ectnNo === null ||
          item.ectnNo === "" ||
          item.ectnNo === undefined
        ) {
          this.passFlag = false;
          return false;
        }
        if (
          item.logisticsService === null ||
          item.logisticsService === "" ||
          item.logisticsService === undefined
        ) {
          this.passFlag = false;
          return false;
        }
        if (
          item.logisticsName === null ||
          item.logisticsName === "" ||
          item.logisticsName === undefined
        ) {
          this.passFlag = false;
          return false;
        }
      });

      if (this.passFlag) {
        let { code } = await OutboundBatchByState_updateIsectn(this.tableDatas);
        if (code === "10000") {
          this.getOutboundTableList();
          this.getStateCount();
          this.visible = false;
        }
      } else {
        this.$message.error("物流商或物流方式及上传文件不能为空！");
      }
    },
    //每一行上传文件
    handleChangeRow(info, data) {
      if (this.uploadFlag) {
        return false;
      }
      if (info.file.status === "done") {
        let response = info.file;
        if (response.response.code === "200") {
          this.$message.success(`${info.file.name} 上传成功`);
          if (!data.ectnFile) {
            data.ectnFile = response.response.responseBody.join(",");
          } else {
            data.ectnFile = data.ectnFile.concat(
              response.response.responseBody
            );
          }
          data.fileName = info.file.name;
          info.fileList = [];
        }
      }

      this.fileList = info.fileList;
      if (info.file.status === "removed") {
        setTimeout(async () => {
          let { code } = await OutboundBatchByState_removefile(
            info.file.response.responseBody
          );
          code;
        }, 50);
      }
    },
    //删除每一行文件
    async delFiles(rowData) {
      let { code } = await OutboundBatchByState_removefile(
        rowData.ectnFile.split(",")
      );
      if (code === "10000") {
        rowData.ectnFile = null;
      }
    },
    //批量导入
    handleChangeUpLoad(info) {
      if (info.fileList.length >= 2) {
        info.fileList = info.fileList.splice(0, 1);
      }
      this.fileListByState = info.fileList;
      this.tableDatas = [];
      if (info.file.status !== "uploading") {
        if (info.fileList[0].response.code === "10000") {
          this.$message.success(`${info.file.name} 导入成功`);
        } else {
          this.$message.error(
            `${info.file.name} 的${info.fileList[0].response.message}`
          );
          return false;
        }
      }
      if (info.file.status !== "uploading") {
        this.tableDatas = info.fileList[0]
          ? info.fileList[0].response.responseBody
          : [];
        if (info.fileList[0].response.responseBody.length >= 1) {
          info.fileList[0].response.responseBody.forEach((item, i) => {
            item.key = i;
          });
        }
      }
    },
  },
  mounted() {
    this.$bus.$off("showOutboundImportModal");
    this.$bus.$on("showOutboundImportModal", () => {
      this.visible = true;
      this.fileList = [];
      this.fileListByState = [];
      this.tableDatas = [];
    });
  },
  computed: {
    ...mapState(["logisticsArray"]),
    columns() {
      return [
        {
          title: "订单编号",
          dataIndex: "orderNumber",
          align: "center",
          // scopedSlots: { customRender: "selfClassifyName" },
          width: "20%",
        },
        {
          title: "物流商",
          dataIndex: "logisticsName",
          align: "center",
          scopedSlots: { customRender: "logisticsName" },

          width: "20%",
        },
        {
          title: "物流方式",
          dataIndex: "logisticsService",
          align: "center",
          scopedSlots: { customRender: "logisticsService" },

          width: "20%",
        },
        {
          title: "物流费用",
          dataIndex: "logisticsCost",
          align: "center",
          scopedSlots: { customRender: "logisticsCost" },

          width: "20%",
        },
        {
          title: "运单号",
          dataIndex: "ectnNo",
          align: "center",
          width: "20%",

          scopedSlots: { customRender: "ectnNo" },
        },
        {
          title: "运单文件",
          dataIndex: "ectnFile",
          scopedSlots: { customRender: "ectnFile" },
          align: "center",
          width: "20%",
        },
      ];
    },
  },
};
</script>

<style lang="less" scoped>
.flie-list {
  display: flex;
  justify-content: space-around;
  a {
    width: 70%;
  }
}
// .ant-upload-list-item-info{}
</style>